<?php

namespace backend\services\order;

use backend\extensions\ApiBaseService;
use common\models\order\OrderRefundModel;
use common\services\order\OrderRefundCommonService;
use api\services\wechat\MiniPayService;
use common\models\order\OrderModel;
use backend\models\config\AdminUser;
use common\services\goods\GoodsStockService;

/**
 * Desc 订单管理服务类
 * @author WMX
 */
class OrderRefundService extends ApiBaseService
{

    /**
     * 列表——获取订单
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        //检索条件
        $condition = ['AND'];
        if ($params['state']) {
            $condition[] = ['=', 'o.state', $params['state'] ?? ''];
        }
        if ($params['order_sn']) {
            $condition[] = ['like', 'o.order_sn', $params['order_sn'] ?? ''];
        }
        if ($params['refund_sn']) {
            $condition[] = ['like', 'o.refund_sn', $params['pay'] ?? ''];
        }
        if ($params['phone']) {
            $condition[] = ['=', 'u.phone', $params['phone'] ?? ''];
        }
        if ($params['time_range']) {
            $condition[] = ['>=', 'o.create_time', $params['time_range'][0] ?? ''];
            $condition[] = ['<', 'o.create_time', $params['time_range'][1] ?? ''];
        }

        $list = OrderRefundCommonService::getUnionAll($condition, $params['page'], $params['page_size']);
        return $list;
    }

    // 获取订单详情
    public static function detail($params)
    {
        $data = OrderRefundCommonService::getOrderDetail($params['refund_sn']);
        return $data;
    }

    // 审核 —— 退款成功——生成销货退款单——完成入库
    public static function check($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $admin = AdminUser::getDataByToken();
            $refund = OrderRefundModel::findOne(['refund_sn' => $params['refund_sn']]);
            if (empty($refund)) {
                throw new \Exception('订单信息异常');
            }
            if ($refund['state'] != OrderRefundModel::STATE_WAIT_AUDIT) {
                throw new \Exception('该订单状态无法操作');
            }
            $order_info = OrderModel::findOne(['order_sn'=>$refund['order_sn']]);
            //通过_修改退款单状态
            $refund->state = 2;
            $refund->examine_id = $admin['id'];
            $refund->examine_time = date('Y-m-d H:i:s');

            $refund_res =  MiniPayService::refund($refund);
            if ($refund_res['code'] != 0) {
                throw new \Exception($refund_res['message']);
            }
            $refund->refund_time = date('Y-m-d H:i:s');
            if (empty($refund->save())) {
                throw new \Exception('退款异常2');
            }
            // 其他业务处理
            $res = self::other($refund);
            if($res['code'] == 1) {
                throw new \Exception('退款异常3');
            }

            //取消券回滚
            if($order_info['coupon_amount'] > 0){
                \api\services\active\ActiveCouponService::rollback($order_info['order_sn']);
            }

            
            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            $transaction->rollBack();
            return self::jsonError($exc->getMessage());
        }
    }


    // 退款之后业务处理
    public static function other($refund)
    {
        try {
            // 修改订单状态
            OrderModel::updateData(['state' => OrderModel::STATE_REFUND, 'refund_time' => date('Y-m-d H:i:s')], ['order_sn' => $refund['order_sn']]);
            $refund_goods_init = json_decode($refund['goods'],true);
            $res = GoodsStockService::release($refund_goods_init);
            if ($res['code'] == 201) {
                throw new \Exception('退款异常');
            }
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }
}
